package me.pearjelly.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import me.pearjelly.model.ImgConvertRule;
import me.pearjelly.model.Pic;
import me.pearjelly.model.ImgConvertRule.Style;
import me.pearjelly.service.ImageService;
import me.pearjelly.util.ImageMagickUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class ImageServiceImpl implements ImageService {

	public void convertImage(Pic pic, String imgFilePath) {
		String key = String.valueOf(pic.getId());
		for (ImgConvertRule rule : imgConvertRules) {
			String outImg = rule.parsePath(key);
			File outImgFile = new File(outImg); 
			if(!outImgFile.getParentFile().exists()){
				outImgFile.getParentFile().mkdirs();
			}
			switch (rule.getStyle()) {
			case AUTO: {
				ImageMagickUtil.convertSmart(imgFilePath, outImg,
						pic.getWidth(), pic.getHeight(), rule.getMaxWidth(),
						rule.getMaxHeight());
				break;
			}
			case FIXHEIGHT: {
				ImageMagickUtil.convertFixedHeight(imgFilePath, outImg,
						pic.getWidth(), pic.getHeight(), rule.getMaxWidth(),
						rule.getMaxHeight());
				break;
			}
			case FIXWIDTH: {
				ImageMagickUtil.convertFixedWidth(imgFilePath, outImg,
						pic.getWidth(), pic.getHeight(), rule.getMaxWidth(),
						rule.getMaxHeight());
				break;
			}
			default:
				break;
			}
		}
	}

	@Override
	public void convertImage(Pic pic, byte[] imageBinaryData) {
		Long id = pic.getId();
		File file = new File(tmpdir + id + "." + pic.getExtension());
		if (file.exists()) {
			file.deleteOnExit();
		}else if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			os.write(imageBinaryData);
		} catch (FileNotFoundException e) {
			logger.error("FileNotFoundException:{}", e.getMessage());
		} catch (IOException e) {
			logger.error("IOException on write:{}", e.getMessage());
		} finally {
			try {
				if (null != os) {
					os.close();
				}
			} catch (IOException e) {
				logger.error("IOException on close:{}", e.getMessage());
			}
		}
		convertImage(pic, file.getAbsolutePath());
		file.deleteOnExit();
	}

	private static final Logger logger = LoggerFactory
			.getLogger(ImageServiceImpl.class);
	private static String PATHREG = "/opt/picapp/WebRoot/out/2008/pic/#tag#/#key#4#6#/#key#2#4#/Img#key#_#tag#.jpg";
	private String tmpdir = "/opt/picapp/WebRoot/catchedImages/";
	private ImgConvertRule[] imgConvertRules = {
			new ImgConvertRule(94, 64, Style.AUTO, "st", PATHREG),
			new ImgConvertRule(130, 85, Style.AUTO, "r", PATHREG),
			new ImgConvertRule(170, 170, Style.AUTO, "s", PATHREG),
			new ImgConvertRule(940, 940, Style.AUTO, "n", PATHREG) };

}
